package com.google.gwt.sample.dynatablerf.client.home;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.sample.dynatablerf.client.AppController;
import com.google.gwt.sample.dynatablerf.client.home.events.GoToProdutoCrudViewEvent;
import com.google.gwt.sample.dynatablerf.client.home.events.GoToProdutoCrudViewEventHandler;
import com.google.gwt.sample.dynatablerf.client.home.presenter.MainPresenter;
import com.google.gwt.sample.dynatablerf.client.home.presenter.ProdutoCrudPresenter;
import com.google.gwt.sample.dynatablerf.client.home.views.MainView;
import com.google.gwt.sample.dynatablerf.client.home.views.ProdutoCrudView;
import com.google.gwt.sample.dynatablerf.shared.AppRequestFactory;
import com.google.gwt.sample.dynatablerf.shared.ProdutoProxy;
import com.google.gwt.user.client.ui.HasWidgets;

public class HomeAppController implements AppController {

	private HasWidgets rootPanel;
	private EventBus eventBus;
	private AppRequestFactory appRequestFactory;
	

	public HomeAppController(HasWidgets container) {
		super();
		this.eventBus = new SimpleEventBus();
		this.rootPanel = container;
		createAppRequestFactory();
	}

	@Override
	public void start() {
		bind();
		openMainView();
		
		
	}

	private void openMainView() {
		MainView mainView = new MainView();
		MainPresenter mainPresenter = new MainPresenter(mainView,eventBus);
		mainPresenter.go(rootPanel);
		
	}

	private void bind() {

		eventBus.addHandler(GoToProdutoCrudViewEvent.TYPE,
				new GoToProdutoCrudViewEventHandler() {

					@Override
					public void onGoToProdutoCrudView(GoToProdutoCrudViewEvent event) {
						openProdutoCrudView(event.getHasWidgets());

					}
				});
	}
	

	private void openProdutoCrudView(HasWidgets hasWidgets) {
		ProdutoCrudView view = new ProdutoCrudView();
		ProdutoCrudPresenter presenter = new  ProdutoCrudPresenter(view,appRequestFactory);
		presenter.go(hasWidgets);
		
	}
	
	private void createAppRequestFactory() {
		appRequestFactory = GWT.create(AppRequestFactory.class);
		appRequestFactory.initialize(eventBus);
	}

}
